package com.loan.controller;
import java.io.File;
import java.io.IOException;

import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.upload.UploadFile;
import com.loan.common.CONST;
import com.loan.util.FileUtil;
import com.loan.util.Json;

/**
 *  文件控制器
 * @since 2017-06-06
 * @author 无处不在的二叔
 */ 
public class FileController extends Controller {
	 
	@Clear  
	public void test() throws IOException { 
		// 获取名称为news的Redis Cache对象
		Cache cache = Redis.use();
	}
	
	/**
	 * 文件上传
	 * @throws IOException 
	 */  
	@Clear
	public void upload() throws IOException { 
		getResponse().setHeader("Access-Control-Allow-Origin","*"); 
		UploadFile f = getFile();
		renderJson(Json.ok("上传成功！",FileUtil.upload(f.getFile())));
	}	

	/**
	 * 文件删除
	 * @throws IOException 
	 */  
	public void del() throws IOException { 	    
		String path = CONST.ROOT+getPara("path"); 
	    String fileName = path;
	    File file = new File(fileName);
	    if (!file.exists() || !file.isFile()) {
			renderJson(Json.error("文件删除失败，原因:" + fileName + "不存在！"));
	    } else { 
	        if (file.delete()) {
	    		renderJson(Json.ok("文件删除成功！"));
	        } else {
	    		renderJson(Json.error("文件删除失败！"));
	        }
	    }
	}	
}